local ngx = ngx
local pcall = pcall
local require = require
local log = require("core.log")
local config = require("conf.config")
local os = os

local _M = {version = 0.1}

local ctx

function _M.http_init()
    -- 加载配置文件
    config.init()
    ctx = require("ctx")
    ctx.init()
end

function _M.http_init_worker()
    local we = require("resty.worker.events")
    local ok, err = we.configure({shm = "worker-events", interval = 0.1})
    if not ok then
        log.error("failed to init worker event: " .. err)
    end

    local worker_id = ngx.worker.id()
    log.info("init worker: ", worker_id)

    ctx.init_worker()
end

--do
--
--    local protocol_handler = {
--        http = function(dispatcher)
--            dispatcher:do_in_rewrite()
--        end,
--        grpc = function()
--            ngx.exec("@grpc_pass")
--        end
--    }
--
--    function _M.http_rewrite()
--        local resp = require("app.core.response")
--        local dispatcher = ctx.get_dispatcher()
--        local protocol = dispatcher.route.protocol
--        local ok = pcall(protocol_handler[protocol], dispatcher)
--        if not ok then
--            log.error("dispatcher error")
--            resp.exit(ngx.HTTP_INTERNAL_SERVER_ERROR, "dispatcher error")
--        end
--    end
--
--end -- do
--
function _M.http_rewrite()
    local dispatcher = ctx.get_dispatcher()
    dispatcher:do_in_access()
end

function _M.http_access()
    local dispatcher = ctx.get_dispatcher()
    dispatcher:do_in_access()
end

function _M.http_content()
    local dispatcher = ctx.get_dispatcher()
    dispatcher:do_in_content()
end

function _M.http_balancer()
    local dispatcher = ctx.get_dispatcher()
    dispatcher:do_in_balancer()
end

function _M.http_header_filter()
    local dispatcher = ctx.get_dispatcher()
    dispatcher:do_in_header_filter()
end

function _M.http_body_filter()
    local dispatcher = ctx.get_dispatcher()
    dispatcher:do_in_body_filter()
end

function _M.http_log()
    local dispatcher = ctx.get_dispatcher()
    dispatcher:do_in_log()
end



return _M
